package com.leetcode.weekly.contest.no285th;

/**
 * @author 覃国强
 * @date 2022-03-20 10:48
 */
public class A02_统计道路上的碰撞次数 {

  static
  class Solution {
    public int countCollisions(String directions) {
      if (directions == null || directions.length() < 2) {
        return 0;
      }
      char[] chars = directions.toCharArray();
      int leftSentinel = -1;
      int rightSentinel = -1;
      for (int i = 0; i < chars.length; ++i) {
        if (chars[i] == 'R' || chars[i] == 'S') {
          leftSentinel = i;
          break;
        }
      }
      for (int i = chars.length - 1; i >= 0; --i) {
        if (chars[i] == 'L' || chars[i] == 'S') {
          rightSentinel = i;
          break;
        }
      }

      int answer = 0;
      for (int i = 0; i < chars.length; ++i) {
        if (chars[i] == 'L' && leftSentinel != -1 && leftSentinel < i) {
          answer += 1;
        }
        if (chars[i] == 'R' && rightSentinel != -1 && rightSentinel > i) {
          answer += 1;
        }
      }
      return answer;
    }
  }

}
